﻿using System;
using System.ComponentModel;
using System.Drawing;
using VisualJS.Kernel;
using VisualJS.Service;
using System.Reflection;
using System.Text; 
namespace VisualJS.Web.Forms
{ 
    [ToolboxItem(true), ToolboxBitmap(typeof(System.Windows.Forms.DateTimePicker)),Description("VisualJS DateTimePicker Control"), DefaultEvent("TextChanged")]
    public class DateTimePicker : MaskedTextBox
    {   
        public DateTimePicker():base("DateTimePicker")
        {
            this.OnCommit = Resources;
            base.Mask = "99/99/9999";
        }

        public override void Extend(ref StringBuilder code)
        {
            code.Append("VSJS['~THIS_COMPONENT'].OnChanged = function(sender, ev){var a=VSJS['~THIS_COMPONENT'];");
            code.Append("pCall['~PARENT_COMPONENT'].SStr(a.Value(),\"Text\",\"~THIS_COMPONENT\");};");
        }
         
        void Resources()
        {
            VisualJS.Kernel.Settings.JQuerySupport = true;

            if (ComponentRegister.Register(typeof(DateTimePicker)))
            {
                Assembly appAsm = Assembly.GetExecutingAssembly();
                ComponentRegister.RegisterFolder(appAsm, "WebControls.calendar");

                ComponentRegister.Merge(new string[]{ 
                    "WebControls.calendar.css.calendar.css",
                    "WebControls.calendar.css.jquery-ui-1.8.17.custom.css"
                    }, "WebControls.calendar.css", "css", Encoding.UTF8);


                ComponentRegister.Merge(new string[]{
                    "WebControls.calendar.js.jquery-ui-1.8.17.custom.min.js",
                    "WebControls.calendar.js.calendar.js"}, "WebControls.calendar.js", "js", Encoding.UTF8);

                string CSS = ComponentRegister.GetText("WebControls.calendar.css", Encoding.UTF8);
                string[] resNames = appAsm.GetManifestResourceNames();
                foreach (string resName in resNames)
                {
                    if (resName.StartsWith("WebControls.calendar.img"))
                    {
                        string fileName = resName.Replace("WebControls.calendar.img.", "");
                        CSS = CSS.Replace("images/" + fileName, "[$$VisualJSResourceTarget$$]?name=" + resName + "&type=image");
                    }
                }
                ComponentRegister.SetText("WebControls.calendar.css", CSS, Encoding.UTF8);
            } 

            this.ClientLoadCheck("WebControls.calendar.js", ClientSideDocuments.Script);
            this.ClientLoadCheck("WebControls.calendar.css", ClientSideDocuments.CSS);
        }

        DateTime maxDate = DateTime.MaxValue;
        public DateTime MaxDate
        {
            get
            {
                return maxDate;
            }
            set
            {
                if( Math.Abs((maxDate-value).TotalHours)>1)
                    SetProperty("MaxDate", value);
                maxDate = value;
            }
        }

        DateTime minDate = DateTime.MinValue;
        public DateTime MinDate
        {
            get
            {
                return minDate;
            }
            set
            {
                if (Math.Abs((minDate - value).TotalHours) > 1)
                    SetProperty("MinDate", value);
                minDate = value;
            }
        }


        string customFormat = "MM/dd/yyyy";
        public string CustomFormat
        {
            get
            {
                return customFormat;
            }
            set
            {
                if (value == customFormat)
                    return;

                string fmat = "";

                foreach (char c in value)
                {
                    if (c == 'm') fmat += "M";
                    else if (c == 'M')
                    {
                        fmat += "m";
                    }
                    else fmat += c.ToString();
                }

                base.Mask = fmat.ToLower().Replace("m", "9").Replace("d", "9").Replace("y", "9");

                fmat = fmat.Replace("yyyy", "yy");
                SetProperty("Format", fmat);
                
                customFormat = value;
            }
        }

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public new string Mask{get { return base.Mask; }set{}}

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public new bool CheckForEmail{get{return base.CheckForEmail;}set{}}

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public new bool PasswordMode{get{return base.PasswordMode;}set{}}

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public new int MinLength { get { return -1; } set { } }

        internal VisualJS.Kernel.Localization localLang = VisualJS.Kernel.Localization.EnglishUS;

        [Browsable(true)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public VisualJS.Kernel.Localization Localize
        {
            get
            {
                return localLang;
            }
            set
            {
                if (value == localLang)
                    return;

                SetProperty("Localization", value.ToString());
                localLang = value;
            }
        }

        DateTime current = DateTime.Now;
        public DateTime Value
        {
            get
            {
                return current;
            }
            set
            {
                if (current == value)
                    return;

                current = value;
                try
                {
                    Text = current.ToString(this.CustomFormat);
                }
                catch
                {
                }
            }
        }

        public override string Text 
        {
            get
            {
                return base.Text;
            }
            set
            {
                if (base.Text == value || value == null)
                    return;

                DateTime dt = DateTime.MinValue;
                if (value.Contains("|"))
                {
                    string[] dts = value.Split('|');
                    int days, month, year;
                    Int32.TryParse(dts[0], out days);
                    Int32.TryParse(dts[1], out month);
                    Int32.TryParse(dts[2], out year);

                    try
                    {
                        dt = new DateTime(year, month, days);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    DateTime.TryParse(value, out dt);
                }
                
                if (dt == DateTime.MinValue)
                    return;

                current = dt;
                base.Text = dt.ToString(customFormat);    
            }
        }
    }
}

